@echo off
chcp 65001 > nul
REM 基本设置
set "projectDir=.\blog_manager"
set "pythonDir=%projectDir%\.venv"
set "pythonBaseDir=%projectDir%\python"
set "djangoVersion=5.0.12"
set "pypiSource=https://pypi.tuna.tsinghua.edu.cn/simple"
set "gitRepo=https://gitee.com/cooltange/blog_manager_2025.git"
set "gitVersion=%1"

REM 检查Git是否安装
where git >nul 2>nul
if %errorlevel% neq 0 (
    echo Git未安装！请先安装Git: https://git-scm.com/downloads
    pause
    exit /b 1
)

REM 删除之前创建的文件夹
echo 删除之前创建的文件夹...
if exist "%pythonDir%" rmdir /s /q "%pythonDir%"
if exist "%projectDir%" rmdir /s /q "%projectDir%"

REM 创建项目目录
echo 创建项目目录: %projectDir%
mkdir "%projectDir%"

REM 解压 Python 3.11.9 便携版本
echo 解压 Python 3.11.9 便携版本...
powershell -Command "Expand-Archive -Path '.\software\python-3.11.9-embed-amd64.zip' -DestinationPath '%pythonBaseDir%' -Force"

REM 配置便携版Python以支持pip和包安装
echo 配置便携版Python...
echo import site >> "%pythonBaseDir%\python311._pth"

REM 安装pip
echo 安装pip...
"%pythonBaseDir%\python.exe" ".\software\get-pip-25.0.1.py" --no-warn-script-location

REM 配置pip默认使用清华源
echo Setting pip mirror to TUNA...
mkdir "%pythonBaseDir%\pip" 2>nul
>"%pythonBaseDir%\pip\pip.ini" (
    echo [global]
    echo index-url = %pypiSource%
)

REM 安装virtualenv
echo Installing virtualenv...
"%pythonBaseDir%\Scripts\pip.exe" install ".\software\virtualenv-20.29.3-py3-none-any.whl"

REM 创建虚拟环境
echo 创建虚拟环境...
"%pythonBaseDir%\Scripts\virtualenv.exe" "%pythonDir%"

REM 安装Django和mysqlclient
echo Installing Django and mysqlclient...
set "PATH=%pythonDir%\Scripts;%PATH%"
"%pythonDir%\Scripts\pip.exe" install "django==%djangoVersion%" --no-warn-script-location
"%pythonDir%\Scripts\pip.exe" install "mysqlclient" --no-warn-script-location

REM Git仓库设置
echo Setting up Git repository...
cd /d "%projectDir%"

REM 初始化Git仓库并拉取代码
git init
git remote add origin %gitRepo%

if "%gitVersion%"=="" (
    echo Pulling latest master branch...
    git pull origin master
) else (
    echo Checking out version: %gitVersion%
    git fetch origin master
    git checkout master
    git reset --hard %gitVersion%
)

REM 切换回基础路径
cd /d "%~dp0"

echo Project setup completed!
pause
